package com.ihelp.rest.utils;

//import java.io.BufferedReader;
//import java.io.BufferedWriter;
//import java.io.InputStreamReader;
//import java.io.OutputStreamWriter;
//import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource; 
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


import java.io.*;
import java.net.*;

public class MailUtil{
 


	/**
	 * 把附件由发件人发给收件人
	 * @param from_user 发件人
	 * @param to_user 收件人
	 * @param file 附件
	 * @param text 文字内容
	 * @throws UnsupportedEncodingException 
	 * @throws MessagingException 
	 */
	public static void sendMail( String from_user,String from_password,String to_user,String to_user_name,String file,String text) 
		throws UnsupportedEncodingException, MessagingException{
		Properties props = new Properties(); 
		props.put("mail.smtp.host","smtp.qq.com"); 
		props.put("mail.smtp.auth","true"); // 是否需要身份验证 
		MyAuthenticator ac = new MyAuthenticator(from_user, from_password);   
		Session session = Session.getInstance(props,ac); 
		//session.setDebug(true);
		// 发件人 
		Address addressFrom = new InternetAddress(from_user+"@qq.com", 
				MimeUtility.encodeWord("爱普科技","utf-8", "Q")); 
		//收件人
		Address addressTo = new InternetAddress(to_user, MimeUtility.encodeWord(to_user_name,"utf-8","Q")); 
		
		MimeBodyPart textBodyPart=new MimeBodyPart(); 
		textBodyPart.setText(text); // 邮件内容 

		MimeBodyPart fileBodyPart=new MimeBodyPart(); 
		FileDataSource fds=new FileDataSource(file);//要发送的附件地址 
		fileBodyPart.setDataHandler(new DataHandler(fds)); 
		fileBodyPart.setFileName(fds.getName());// 设置附件的名称
		
		Multipart container=new MimeMultipart(); 
		container.addBodyPart(textBodyPart); 
		container.addBodyPart(fileBodyPart); 
		Transport transport = null;
		try{
			MimeMessage message = new MimeMessage(session); 
			message.setSentDate(new Date());// 设置发送时间 
			message.setSubject("会员邮件服务","utf-8");// 设置邮件主题的编码格式 
			message.setFrom(addressFrom); // 发件人 
			if(null != addressTo){
				message.addRecipient(Message.RecipientType.TO,addressTo);// 收件人 
			} 
			message.setContent(container); // 添加 文本文件和附件 
			message.saveChanges(); 
			transport = session.getTransport("smtp"); 
			transport.connect("smtp.qq.com", from_user,from_password);
			/*if(check(to_user)){
				Transport.send(message); 
			}else{
				System.out.println("------无效地址-------"+to_user);
			}*/
			Transport.send(message); 
		}catch(Exception mex) { 
	        //System.out.println("send failed, exception: " ); 
			mex.printStackTrace();
	    }finally{
			transport.close(); 
	    }
	}

/*	 public static boolean check(String mailTo)
	    {
	        if (!mailTo.matches("w+([-_.]w+)*@w+([-.]w+)*.w+([-.]w+)*")) { //判断格式
	            return false;
	         }
	         String hostName = mailTo.split("@")[1];  //获得如163.com
	         String host = null;  // MX记录
	        
	        try {
	             Lookup lookup = new Lookup(hostName, Type.MX);
	             lookup.run();
	            if (lookup.getResult() != Lookup.SUCCESSFUL) {
	                return false;
	             }
	            else {
	                 Record[] result = lookup.getAnswers();
	                 host = result[0].getAdditionalName().toString();
	             }
	            
	             Socket socket = new Socket(host, 25);
	             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
	             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	             in.readLine();
	             out.write("HELO Sender ");
	             out.flush();
	             in.readLine();
	             out.write("MAIL FROM:<xx@xxx.xx> ");
	             out.flush();
	             in.readLine();
	             out.write("RCPT TO:<" + mailTo + "> ");
	             out.flush();
	             String r = in.readLine();
	             out.write("QUIT ");
	             out.flush();
	            
	             out.close();
	             in.close();
	             socket.close();
	            if (!r.startsWith("250")) {
	                return false;
	             }
	            else {
	                return true;
	             }
	         } catch (Exception e) {
	            return false;
	         }
	     }*/
}
